import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import { Input, Button, message, Avatar, Typography } from 'antd';
import { SendOutlined, UserOutlined, RobotOutlined, MinusOutlined, MessageOutlined } from '@ant-design/icons';

const { TextArea } = Input;
const { Text } = Typography;

const IntelligentAgent = ({ currentUser }) => {
  const [messages, setMessages] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [sessionId, setSessionId] = useState(null);
  const [isMinimized, setIsMinimized] = useState(false);
  const messagesEndRef = useRef(null);

  const createAgentSession = async () => {
    try {
      const res = await axios.post('http://localhost:5001/api/agent/sessions', {
        userId: currentUser.id,
        username: currentUser.username,
        role: currentUser.role,
        fullName: currentUser.full_name
      });
      setSessionId(res.data.sessionId);
      
      // 添加欢迎消息
      setMessages([
        {
          id: Date.now(),
          text: '🤖 欢迎使用智能任务助手！\n\n我现在具备以下能力：\n• 📝 创建任务（如：创建周报任务给张三）\n• 🔍 智能分析当前页面内容和DOM结构\n• 🎯 自动识别页面可交互元素\n• 🚀 基于自然语言指令执行页面操作\n• 📊 查看数据统计和报表\n• ❓ 回答系统使用问题\n\n💡 现在我会结合当前页面的DOM信息来理解您的指令，并且所有的分析过程都会展示给您！\n\n请告诉我您需要什么帮助！',
          sender: 'agent',
          timestamp: new Date()
        }
      ]);
    } catch (error) {
      console.error('Failed to create agent session:', error);
      message.error('智能助手连接失败，请稍后重试');
    }
  };

  const closeAgentSession = async () => {
    try {
      await axios.delete(`http://localhost:5001/api/agent/sessions/${sessionId}`);
    } catch (error) {
      console.error('Failed to close agent session:', error);
    }
  };

  // 创建会话
  useEffect(() => {
    if (currentUser) {
      createAgentSession();
    }

    // 组件卸载时关闭会话
    return () => {
      if (sessionId) {
        closeAgentSession();
      }
    };
  }, [currentUser, sessionId]);

  // 滚动到最新消息
  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  // 获取详细的DOM信息
  const getDetailedDOMInfo = () => {
    try {
      // 获取所有可交互元素的详细信息
      const interactiveElements = [];
      const selectors = [
        'input', 'button', 'select', 'textarea', 'a',
        '[onclick]', '[role="button"]', '[tabindex]',
        '.btn', '.button', '.link', '.nav-item', '.ant-btn',
        '.notification-item', '.user-item', '.task-item'
      ];

      selectors.forEach(selector => {
        const elements = document.querySelectorAll(selector);
        elements.forEach((el, index) => {
          if (el.offsetParent !== null) { // 只获取可见元素
            const rect = el.getBoundingClientRect();
            const styles = window.getComputedStyle(el);

            interactiveElements.push({
              tagName: el.tagName.toLowerCase(),
              type: el.type || 'unknown',
              id: el.id || '',
              className: el.className || '',
              text: el.textContent?.trim().substring(0, 200) || '',
              placeholder: el.placeholder || '',
              name: el.name || '',
              value: el.value || '',
              href: el.href || '',
              title: el.title || '',
              ariaLabel: el.getAttribute('aria-label') || '',
              dataTestId: el.getAttribute('data-testid') || '',
              selector: generateSelector(el),
              position: {
                x: Math.round(rect.x),
                y: Math.round(rect.y),
                width: Math.round(rect.width),
                height: Math.round(rect.height)
              },
              isVisible: styles.display !== 'none' && styles.visibility !== 'hidden',
              isClickable: el.tagName === 'BUTTON' || el.tagName === 'A' || el.onclick || styles.cursor === 'pointer',
              index: index
            });
          }
        });
      });

      // 获取表单信息
      const forms = Array.from(document.forms).map(form => ({
        id: form.id,
        name: form.name,
        action: form.action,
        method: form.method,
        elements: Array.from(form.elements).map(el => ({
          name: el.name,
          type: el.type,
          value: el.value,
          required: el.required,
          placeholder: el.placeholder
        }))
      }));

      // 获取页面结构信息
      const headings = Array.from(document.querySelectorAll('h1, h2, h3, h4, h5, h6')).map(h => ({
        level: parseInt(h.tagName.substring(1)),
        text: h.textContent.trim(),
        id: h.id
      }));

      // 获取导航信息
      const navigation = Array.from(document.querySelectorAll('nav, .nav, .navigation, .menu')).map(nav => ({
        className: nav.className,
        items: Array.from(nav.querySelectorAll('a, button')).map(item => ({
          text: item.textContent.trim(),
          href: item.href,
          className: item.className
        }))
      }));

      return {
        title: document.title,
        url: window.location.href,
        pathname: window.location.pathname,
        search: window.location.search,
        hash: window.location.hash,
        bodyText: document.body.innerText.substring(0, 3000),
        interactiveElements: interactiveElements,
        forms: forms,
        headings: headings,
        navigation: navigation,
        metaInfo: {
          charset: document.characterSet,
          lang: document.documentElement.lang,
          viewport: document.querySelector('meta[name="viewport"]')?.content
        },
        timestamp: new Date().toISOString()
      };
    } catch (error) {
      console.error('获取DOM信息失败:', error);
      return {
        title: document.title,
        url: window.location.href,
        timestamp: new Date().toISOString(),
        error: error.message
      };
    }
  };

  // 生成CSS选择器
  const generateSelector = (element) => {
    if (element.id) {
      return `#${element.id}`;
    }

    let selector = element.tagName.toLowerCase();

    if (element.className) {
      const classes = element.className.split(' ').filter(c => c.trim());
      if (classes.length > 0) {
        selector += '.' + classes.slice(0, 2).join('.');
      }
    }

    if (element.name) {
      selector += `[name="${element.name}"]`;
    }

    return selector;
  };

  const handleSendMessage = async () => {
    if (!inputValue.trim() || !sessionId || isLoading) {
      return;
    }

    const userMessage = {
      id: Date.now(),
      text: inputValue.trim(),
      sender: 'user',
      timestamp: new Date()
    };

    setMessages(prev => [...prev, userMessage]);
    setIsLoading(true);

    try {
      console.log('发送命令到智能体服务:', inputValue.trim());

      // 获取详细的DOM信息
      let detailedDOMInfo = null;
      try {
        detailedDOMInfo = getDetailedDOMInfo();
        console.log('DOM信息获取成功:', detailedDOMInfo?.interactiveElements?.length || 0, '个可交互元素');
      } catch (domError) {
        console.error('获取DOM信息失败:', domError);
        detailedDOMInfo = {
          title: document.title,
          url: window.location.href,
          timestamp: new Date().toISOString(),
          error: '获取DOM信息失败',
          interactiveElements: [],
          forms: [],
          headings: []
        };
      }

      const res = await axios.post(
        `http://localhost:5001/api/agent/sessions/${sessionId}/execute`,
        {
          command: inputValue.trim(),
          domInfo: detailedDOMInfo,
          pageContext: {
            url: window.location.href,
            title: document.title,
            userAgent: navigator.userAgent,
            timestamp: new Date().toISOString()
          }
        }
      );
      console.log('收到智能体响应:', res.data);

      // 格式化大模型分析结果
      let displayText = res.data.message;

      // 如果有详细的分析结果，添加到显示文本中
      if (res.data.analysis) {
        const analysis = res.data.analysis;

        // 添加分析摘要
        if (analysis.summary) {
          displayText += `\n\n📋 分析摘要: ${analysis.summary}`;
        }

        // 添加原始分析结果
        if (analysis.rawAnalysis && analysis.rawAnalysis !== analysis.summary) {
          displayText += `\n\n🤖 大模型分析:\n${analysis.rawAnalysis}`;
        }

        // 添加推荐步骤
        if (analysis.recommendedSteps && analysis.recommendedSteps.length > 0) {
          displayText += '\n\n🚀 推荐操作步骤:';
          analysis.recommendedSteps.forEach((step, index) => {
            displayText += `\n${index + 1}. ${step.action}`;
            if (step.selector) {
              displayText += ` (选择器: ${step.selector})`;
            }
            if (step.value) {
              displayText += ` (值: ${step.value})`;
            }
            if (step.description) {
              displayText += ` - ${step.description}`;
            }
          });
        }

        // 添加识别的可交互元素
        if (analysis.interactiveElements && analysis.interactiveElements.length > 0) {
          displayText += `\n\n🎯 识别的可交互元素 (${analysis.interactiveElements.length}个):`;
          analysis.interactiveElements.slice(0, 5).forEach((element, index) => {
            displayText += `\n${index + 1}. ${element.type}: "${element.description || element.text || element.selector}"`;
          });
          if (analysis.interactiveElements.length > 5) {
            displayText += `\n... 还有${analysis.interactiveElements.length - 5}个元素`;
          }
        }

        // 添加页面功能分析
        if (analysis.pageFunction) {
          displayText += `\n\n📄 页面功能: ${analysis.pageFunction}`;
        }

        // 添加置信度
        if (analysis.confidence !== undefined) {
          displayText += `\n\n🎯 分析置信度: ${(analysis.confidence * 100).toFixed(1)}%`;
        }
      }

      // 添加DOM信息摘要
      if (res.data.domInfo) {
        const domInfo = res.data.domInfo;
        displayText += `\n\n📊 页面信息摘要:`;
        displayText += `\n• 页面标题: ${domInfo.title}`;
        displayText += `\n• 可交互元素: ${domInfo.interactiveElements?.length || 0} 个`;
        displayText += `\n• 表单数量: ${domInfo.forms?.length || 0} 个`;
        displayText += `\n• 标题层级: ${domInfo.headings?.length || 0} 个`;
      }
      
      const agentMessage = {
        id: Date.now() + 1,
        text: displayText,
        sender: 'agent',
        success: res.data.success,
        timestamp: new Date(),
        rawData: res.data // 保存原始数据用于调试
      };

      setMessages(prev => [...prev, agentMessage]);

      if (res.data.success) {
        message.success('任务执行成功');
        // 不再自动刷新页面，保持对话框中的结果可见
      } else {
        message.error('任务执行失败');
      }
    } catch (error) {
      console.error('Failed to execute command:', error);
      console.error('Error details:', {
        message: error.message,
        status: error.response?.status,
        statusText: error.response?.statusText,
        data: error.response?.data
      });

      let errorText = '执行命令时发生错误，请稍后重试';

      // 提供更详细的错误信息
      if (error.response) {
        if (error.response.status === 404) {
          errorText = '智能助手服务不可用 (404)，请检查服务是否正常运行';
        } else if (error.response.status === 500) {
          errorText = `服务器内部错误 (500): ${error.response.data?.error || '未知错误'}`;
        } else if (error.response.status === 0 || error.code === 'NETWORK_ERROR') {
          errorText = '网络连接错误，请检查智能助手服务是否启动 (端口5001)';
        } else {
          errorText = `请求失败 (${error.response.status}): ${error.response.statusText}`;
        }
      } else if (error.code === 'ECONNREFUSED') {
        errorText = '无法连接到智能助手服务，请确认服务已启动';
      } else if (error.message.includes('Network Error')) {
        errorText = '网络错误，请检查智能助手服务 (http://localhost:5001)';
      }

      const errorMessage = {
        id: Date.now() + 1,
        text: errorText,
        sender: 'agent',
        success: false,
        timestamp: new Date(),
        errorDetails: {
          originalError: error.message,
          statusCode: error.response?.status,
          responseData: error.response?.data
        }
      };
      setMessages(prev => [...prev, errorMessage]);
      message.error('执行命令失败');
    } finally {
      setIsLoading(false);
      setInputValue(''); // 在消息发送完成后才清空输入框
    }
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  const messageList = messages.map(message => (
    <div key={message.id} className={`message ${message.sender}`}>
      <div className="message-container">
        <Avatar
          icon={message.sender === 'user' ? <UserOutlined /> : <RobotOutlined />}
          className="message-avatar"
          style={{
            backgroundColor: message.sender === 'user' ? '#1890ff' : '#52c41a',
            margin: '0 10px 0 0'
          }}
        />
        <div className="message-content">
          <div 
            className="message-bubble"
            style={{
              backgroundColor: message.sender === 'user' ? '#1890ff' : '#f0f0f0',
              color: message.sender === 'user' ? '#fff' : '#333'
            }}
          >
            <Text>{message.text}</Text>
          </div>
          <div className="message-time">
            {message.timestamp.toLocaleTimeString('zh-CN', {
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit'
            })}
          </div>
        </div>
      </div>
    </div>
  ));

  // 最小化状态下的图标模式
  if (isMinimized) {
    return (
      <div className="intelligent-agent-minimized">
        <div 
          className="agent-minimized-icon"
          onClick={() => setIsMinimized(false)}
          title="点击展开智能助手"
        >
          <Avatar 
            icon={<MessageOutlined />} 
            style={{ backgroundColor: '#1890ff' }}
          />
          {messages.length > 0 && (
            <span className="unread-badge">
              {messages.length}
            </span>
          )}
        </div>
      </div>
    );
  }

  return (
    <div className="intelligent-agent">
      <div className="agent-header">
        <div className="agent-header-left">
          <Avatar icon={<RobotOutlined />} />
          <h3>智能任务助手</h3>
        </div>
        <div className="agent-header-actions">
          <Button
            type="text"
            icon={<MinusOutlined />}
            onClick={() => setIsMinimized(true)}
            title="最小化"
          />
        </div>
      </div>
      
      <div className="agent-messages">
        {messageList}
        <div ref={messagesEndRef} />
      </div>
      
      <div className="agent-input-area">
        <TextArea
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          onKeyPress={handleKeyPress}
          placeholder="请输入任何指令，例如：分析这个页面、帮我点击登录按钮、创建一个任务给张三、解释页面上的图表等"
          rows={2}
          disabled={isLoading || !sessionId}
        />
        <Button
          type="primary"
          icon={<SendOutlined />}
          onClick={handleSendMessage}
          loading={isLoading}
          disabled={!inputValue.trim() || isLoading || !sessionId}
          className="send-button"
        >
          发送
        </Button>
      </div>

      <style jsx>{
        `.intelligent-agent {
          position: fixed;
          bottom: 20px;
          right: 20px;
          width: 400px;
          height: 600px;
          background: #fff;
          border-radius: 8px;
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
          display: flex;
          flex-direction: column;
          z-index: 1000;
        }

        .intelligent-agent-minimized {
          position: fixed;
          bottom: 20px;
          right: 20px;
          z-index: 1000;
        }

        .agent-minimized-icon {
          position: relative;
          cursor: pointer;
          transition: transform 0.2s;
        }

        .agent-minimized-icon:hover {
          transform: scale(1.1);
        }

        .unread-badge {
          position: absolute;
          top: -5px;
          right: -5px;
          background-color: #ff4d4f;
          color: white;
          border-radius: 50%;
          width: 18px;
          height: 18px;
          font-size: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .agent-header {
          padding: 16px;
          background: #f0f2f5;
          border-top-left-radius: 8px;
          border-top-right-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          border-bottom: 1px solid #e8e8e8;
        }

        .agent-header-left {
          display: flex;
          align-items: center;
        }

        .agent-header h3 {
          margin: 0 0 0 10px;
          font-size: 16px;
          color: #333;
        }

        .agent-header-actions {
          display: flex;
          align-items: center;
        }

        .agent-messages {
          flex: 1;
          overflow-y: auto;
          padding: 16px;
          background: #fafafa;
        }

        .message {
          margin-bottom: 16px;
          display: flex;
          flex-direction: column;
        }

        .message.user {
          align-items: flex-end;
        }

        .message.agent {
          align-items: flex-start;
        }

        .message-container {
          display: flex;
          align-items: flex-start;
          max-width: 80%;
        }

        .message-avatar {
          flex-shrink: 0;
        }

        .message-content {
          display: flex;
          flex-direction: column;
        }

        .message-bubble {
          padding: 10px 14px;
          border-radius: 18px;
          word-wrap: break-word;
        }

        .message-time {
          font-size: 12px;
          color: #999;
          margin-top: 4px;
          text-align: center;
        }

        .agent-input-area {
          padding: 16px;
          background: #fff;
          border-top: 1px solid #e8e8e8;
        }

        .send-button {
          margin-top: 8px;
          width: 100%;
        }

        @media (max-width: 768px) {
          .intelligent-agent {
            width: 100%;
            height: 100%;
            bottom: 0;
            right: 0;
            border-radius: 0;
          }
        }`
      }</style>
    </div>
  );
};

export default IntelligentAgent;